<?php

/**
* alltosun.com 微信简单的网页授权 index.php
* ============================================================================
* 版权所有 (C) 2009-2013 北京互动阳光科技有限公司，并保留所有权利。
* 网站地址: http://www.alltosun.com
* ----------------------------------------------------------------------------
* 许可声明：这是一个开源程序，未经许可不得将本软件的整体或任何部分用于商业用途及再发布。
* ============================================================================
* $Author: 钱有明 (qianym@alltosun.com) $
* $Date: 2013-12-30 下午2:24:26 $
* $Id$
*/

class Action
{
    private $appid;
    private $appsecret;

    public function __construct()
    {
        $this->user_id = user_helper::get_user_id();
        $openapi = Config::get('openapi');
        $this->appid = $openapi['weixin'][0];
        $this->appsecret = $openapi['weixin'][1];

    }

    public function index()
    {
        $redirect_url = Request::getParam('redirect_url', '');
        $_SESSION['redirect_url'] = $redirect_url;
        $redirect_uri = AnUrl('openapi/weixin/simple/callback');
        $redirect_uri = urlencode($redirect_uri);
        $url = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid='.$this->appid.'&redirect_uri='.$redirect_uri.'&response_type=code&scope=snsapi_base&state=123#wechat_redirect';
        Response::redirect($url);
    }

    public function callback()
    {
        $code = Request::getParam('code');

        $url = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid='.$this->appid.'&secret='.$this->appsecret.'&code='.$code.'&grant_type=authorization_code';

        $list = curl_request($url, 'get');
        $list = json_decode($list, true);

        $open_id = 0;
        if (isset($list['openid']) && $list['openid']) {
            $open_id = $list['openid'];
        }

        if (!$open_id) {
            return array('请确保网络顺畅，返回重试', 'error', AnUrl($_SESSION['redirect_url']));
        }
        $openid_info = _uri('weixin_openid', array('user_id'=>$this->user_id));
        if($openid_info) {
            $_SESSION['open_id'] = $openid_info['open_id'];
            $affected = _model('weixin_openid')->update($openid_info['id'], array('open_id'=>$open_id));
        } else {
            $openid_id = _model('weixin_openid')->create(array('open_id'=>$open_id, 'user_id' => $this->user_id));
            $_SESSION['open_id'] = $open_id;
        }
        if(isset($_SESSION['redirect_url']) && !empty($_SESSION['redirect_url'])) {
            Response::redirect(AnUrl($_SESSION['redirect_url']));
        } else {
            Response::redirect(AnUrl('order/trade'));
        }
    }
}
?>